/**
 * FyLLGen - A Java based tool for collecting and distributing family data
 *
 * Copyright (C) 2007-2011 Christian Packenius
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.chris_soft.fyllgen.utilities;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import de.chris_soft.fyllgen.Statics;

/**
 * Statische Routinen rund um das Thema "Erzeugen von Backups".
 * @author Christian Packenius, 07.09.2011.
 */
public class Backup {
  /**
   * Erzeugt ein Backup der angegebenen Datei, insofern diese existiert.
   * @param filename Originaldatei.
   * @return <i>true</i> if the backup has been successfully created,
   *         <i>false</i> otherwise.
   */
  public static boolean createBackup(String filename) {
    new File(Statics.BACKUPS_PATH).mkdir();

    File file = new File(filename);
    if (!file.exists()) {
      return false;
    }

    InputStream in = null;
    OutputStream out = null;

    String backup = Statics.BACKUPS_PATH + "/" + Statics.getUniqueID() + "." + file.getName() + ".bak";

    try {
      in = new BufferedInputStream(new FileInputStream(file));
      out = new BufferedOutputStream(new FileOutputStream(backup));
      IOTools.copyStream(in, out);
    }
    catch (IOException ioe) {
      return false;
    }
    finally {
      try {
        if (out != null) {
          out.close();
        }
      }
      catch (IOException e) {
        // Ignorieren.
      }
      try {
        if (in != null) {
          in.close();
        }
      }
      catch (IOException e) {
        // Ignorieren.
      }
    }

    return true;
  }
}
